package com.wangsd.web.controller;

import com.alibaba.fastjson.JSON;
import com.wangsd.core.entity.JSONResult;
import com.wangsd.core.util.ApplicationUtils;
import com.wangsd.core.util.DateUtils;
import com.wangsd.core.util.PrintMessage;
import com.wangsd.core.util.StaticVar;
import com.wangsd.web.model.*;
import com.wangsd.web.modelCustom.*;
import com.wangsd.web.service.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 账单管理Controller
 */
@Controller
@RequestMapping("/billAccount")
public class BillAccountController {
    private static final Logger logger = LogManager.getLogger(BillAccountController.class.getName());
    @Autowired
    BillAccountService billAccountService;
    @Autowired
    RoominfoService roominfoService;
    @Autowired
    HousinginfoService housinginfoService;
    @Autowired
    AlipayService alipayService;
    @Autowired
    PrintService printService;
    @Autowired
    CosttypeService costtypeService;
    @Autowired
    PropertyinfoService propertyinfoService;
    @Autowired
    DirectFeeService directFeeService;

    /**
     * 根据部门code查询账单信息
     *
     * @param query
     * @return
     */
    @RequestMapping("/billAccountList")
    public String billAccountList(BillAccountCustom query, HttpServletRequest request, Model model) {
        UserCustom loginUser = (UserCustom) request.getSession().getAttribute("userInfo");
        String parentCode = loginUser.getParentCode();
        List<ParentCustom> parentList = housinginfoService.queryParentHousingByCode(loginUser.getParentCode());
        model.addAttribute("parentList", parentList);
        query.setHousingCode(parentCode);
        List<Costtype> costList = costtypeService.queryAllList();
        model.addAttribute("costList", costList);
        /*List<BillAccountCustom> list = billAccountService.queryBillAccountList(query);
        model.addAttribute("billaccountList", list);*/
        model.addAttribute("query", query);
        return "/billaccount/billaccount-list";
    }

    /**
     * 根据部门code查询账单信息
     *
     * @param query
     * @return
     */
    @RequestMapping("/tableBillAccountList")
    @ResponseBody
    public DataTable tableBillAccountList(BillAccountCustom query, HttpServletRequest request) {
        DataTable table = new DataTable();
        UserCustom loginUser = (UserCustom) request.getSession().getAttribute("userInfo");
        String parentCode = loginUser.getParentCode();
        query.setHousingCode(parentCode);
        List<BillAccountCustom> list = billAccountService.queryBillAccountList(query);
        Integer account = billAccountService.queryBillAccountListAccount(query);
        table.setRecordsFiltered(account);
        table.setRecordsTotal(account);
        if (list.size() != 0) {
            table.setData(list);
        } else {
            BillAccountCustom billAccountCustom = new BillAccountCustom();
            billAccountCustom.setAccountSum("0");
            list.add(billAccountCustom);
            table.setData(list);
        }
        return table;
    }


    /**
     * 电子发票
     *
     * @param query
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/invoiceList")
    public String invoiceList(BillAccountCustom query, HttpServletRequest request, Model model) {
        UserCustom loginUser = (UserCustom) request.getSession().getAttribute("userInfo");
        List<ParentCustom> parentList = housinginfoService.queryParentHousingByCode(loginUser.getParentCode());
        model.addAttribute("parentList", parentList);
        List<Costtype> costList = costtypeService.queryAllList();
        model.addAttribute("costList", costList);

        String parentCode = loginUser.getParentCode();
        query.setHousingCode(parentCode);
        query.setPaystatus(true);
        return "/billaccount/invoice-list";
    }

    /**
     * 电子发票查询
     *
     * @param query
     * @param request
     * @return
     */
    @RequestMapping("/tableInvoiceList")
    @ResponseBody
    public DataTable tableInvoiceList(BillAccountCustom query, HttpServletRequest request) {
        DataTable dataTable = new DataTable();
        UserCustom loginUser = (UserCustom) request.getSession().getAttribute("userInfo");
        String parentCode = loginUser.getParentCode();
        query.setHousingCode(parentCode);
        query.setPaystatus(true);
        List<BillAccountCustom> list = billAccountService.queryBillAccountList(query);
        Integer billCount = billAccountService.queryBillAccountListAccount(query);
        dataTable.setRecordsFiltered(billCount);
        dataTable.setRecordsTotal(billCount);
        dataTable.setData(list);
        return dataTable;
    }

    /**
     * 跳转新增账单
     *
     * @param
     * @return
     */
    @RequestMapping("/addBillAccount")
    public String addBillAccount(HttpServletRequest request, Model model) {
        UserCustom loginUser = (UserCustom) request.getSession().getAttribute("userInfo");
        List<ParentCustom> parentList = housinginfoService.queryParentHousingByCode(loginUser.getParentCode());
        model.addAttribute("parentList", parentList);
        List<Costtype> costList = costtypeService.queryAllList();
        model.addAttribute("costList", costList);
        return "/billaccount/billaccount-add";
    }

    /**
     * 跳转编辑账单
     *
     * @param
     * @return
     */
    @RequestMapping("/updateBillAccount")
    public String updateBillAccount(Integer id, HttpServletRequest request, Model model) {
        List<Costtype> costList = costtypeService.queryAllList();
        model.addAttribute("costList", costList);
        BillAccountCustom query = new BillAccountCustom();
        query.setId(id);
        List<BillAccountCustom> list = billAccountService.queryBillAccountList(query);
        if (list.size() == 1) {
            BillAccountCustom billaccount = list.get(0);
            model.addAttribute("billaccount", billaccount);
        }
        return "/billaccount/billaccount-update";
    }

    /**
     * 跳转编辑备注
     *
     * @param
     * @return
     */
    @RequestMapping("/updateRemarke")
    public String updateRemarke(Integer id, HttpServletRequest request, Model model) {
        BillAccountCustom query = new BillAccountCustom();
        query.setId(id);
        List<BillAccountCustom> list = billAccountService.queryBillAccountList(query);
        if (list.size() == 1) {
            BillAccountCustom billaccount = list.get(0);
            model.addAttribute("billaccount", billaccount);
        }
        return "/billaccount/remarke";
    }

    /**
     * 跳转账单收款
     *
     * @param
     * @return
     */
    @RequestMapping("/openReceivBillAccount")
    public String openReceivBillAccount(Integer id, HttpServletRequest request, Model model) {
        List<Costtype> costList = costtypeService.queryAllList();
        model.addAttribute("costList", costList);
        BillAccountCustom query = new BillAccountCustom();
        query.setId(id);
        List<BillAccountCustom> list = billAccountService.queryBillAccountList(query);
        if (list.size() == 1) {
            BillAccountCustom billaccount = list.get(0);
            model.addAttribute("billaccount", billaccount);
        }
        return "/billaccount/billaccount-receiv";
    }

    /**
     * 保存账单
     *
     * @param billaccount
     * @return
     */
    @RequestMapping(path = "/saveOrUpdateBillAccount", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult saveOrUpdateBillAccount(Billaccount billaccount, HttpSession session) {
        boolean bl = false;
        JSONResult obj = new JSONResult();
        BillAccountCustom bill = new BillAccountCustom();
        if (billaccount.getId() == null) {
            bill.setHousingId(billaccount.getHousingId());
            bill.setRoominfoId(billaccount.getRoominfoId());
            bill.setCostType(billaccount.getCostType());
            bill.setAcctPeriod(billaccount.getAcctPeriod());
            bill.setBillEntryAmount(billaccount.getBillEntryAmount());
            bill.setAcctPeriod(billaccount.getAcctPeriod());
            List<BillAccountCustom> billCustom = billAccountService.queryBillAccountList(bill);
            if (billCustom.size() == 0) {
                billaccount.setCreateTime(new Date());
                bl = billAccountService.insertBillaccount(billaccount);
            } else {
                bl = false;
                obj.setMessage("账单信息已存在！");
            }
        } else {
            Billaccount oldBill = billAccountService.selectBillAccountById(billaccount.getId());
            if (oldBill.getStatus()) {
                UserCustom loginUser = (UserCustom) session.getAttribute("userInfo");
                HousinginfoCustom housing = housinginfoService.selectHousingCustomById(oldBill.getHousingId());
                List<BillAccountCustom> billList = new ArrayList<>();
                BillAccountCustom custom = new BillAccountCustom();
                BeanUtils.copyProperties(billaccount, custom);
                billList.add(custom);

                billAccountService.updateBillaccount(billaccount);
                bl = alipayService.billModifyRequest(housing.getCommunityId(), billList, housing.getToken(), loginUser);

            } else {
                bl = billAccountService.updateBillaccount(billaccount);
            }
        }
        obj.setSuccess(bl);
        return obj;
    }

    /**
     * 编辑备注
     *
     * @param billaccount
     * @param session
     * @return
     */
    @RequestMapping(path = "/updateRemarke", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateRemarke(Billaccount billaccount, HttpSession session) {
        boolean bl = billAccountService.updateBillaccount(billaccount);
        JSONResult obj = new JSONResult();
        obj.setSuccess(bl);
        return obj;
    }

    @RequestMapping("/deleteBillaccount")
    @ResponseBody
    public JSONResult deleteBillaccount(Integer[] ids, HttpSession session) {
        JSONResult jsonResult = new JSONResult();
        boolean bl = false;
        for (Integer id : ids) {
            Billaccount oldBill = billAccountService.selectBillAccountById(id);
            if (oldBill.getPaystatus()) {
                jsonResult.setMessage("已支付不允许删除");
                jsonResult.setSuccess(false);
                return jsonResult;
            } else {
                if (oldBill.getStatus()) { //已同步
                    //获取公钥 私钥
                    UserCustom loginUser = (UserCustom) session.getAttribute("userInfo");
                    HousinginfoCustom housing = housinginfoService.selectHousingCustomById(oldBill.getHousingId());
                    List<String> roomids = new ArrayList<>();
                    roomids.add(oldBill.getId().toString());
                    bl = alipayService.billDeleteRequest(housing.getCommunityId(), roomids, housing.getToken(), loginUser);
                    if (bl) {
                        bl = billAccountService.deleteBillaccount(id);
                    }
                } else {
                    bl = billAccountService.deleteBillaccount(id);
                }
            }
        }
        if (bl) {
            jsonResult.setMessage("删除成功");
        } else {
            jsonResult.setMessage("删除失败");
        }
        jsonResult.setSuccess(bl);
        return jsonResult;
    }

    /**
     * @param id
     * @param session
     * @Author:qc
     * @Description: 删除已付款
     * @Date:11:08 2017/12/21
     */
    @RequestMapping("/deleteBillaccountPay")
    @ResponseBody
    public JSONResult deleteBillaccountPay(Integer id, HttpSession session) {
        JSONResult jsonResult = new JSONResult();
        boolean bl = billAccountService.deleteBillaccount(id);
        if (bl) {
            jsonResult.setMessage("删除成功");
        } else {
            jsonResult.setMessage("删除失败");
        }
        jsonResult.setSuccess(bl);
        return jsonResult;
    }

    /**
     * 账单收款
     *
     * @param billaccount
     * @return
     */
    @RequestMapping(path = "/receivBillAccount", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult receivBillAccount(Billaccount billaccount, HttpSession session) {
        boolean bl = false;
        JSONResult jsonResult = new JSONResult();
        //删除支付宝账单
        Billaccount oldBill = billAccountService.selectBillAccountById(billaccount.getId());
        if (oldBill.getStatus()) {
            UserCustom loginUser = (UserCustom) session.getAttribute("userInfo");
            HousinginfoCustom housing = housinginfoService.selectHousingCustomById(oldBill.getHousingId());
            List<String> bill_entry_id_list = new ArrayList<>();
            bill_entry_id_list.add(oldBill.getId().toString());
            alipayService.billDeleteRequest(housing.getCommunityId(), bill_entry_id_list, housing.getToken(), loginUser);
        }
        //更新收款信息
        billaccount.setPaystatus(true);
        billaccount.setPaydate(new Date());
        bl = billAccountService.updateBillaccount(billaccount);

        //打印小票
        Integer[] idsInt = new Integer[1];
        idsInt[0] = billaccount.getId();
        printAccount(idsInt);
        jsonResult.setSuccess(bl);
        return jsonResult;
    }

    /**
     * 小票打印
     *
     * @param id
     * @return
     */
    @RequestMapping(path = "/printAccount")
    @ResponseBody
    public JSONResult printAccount(Integer[] id) {
        boolean bl = false;
        JSONResult jsonResult = new JSONResult();
        Double totalPrice = 0.0;
        for (int i = 0; i < id.length; i++) {
            Billaccount oldBill = billAccountService.selectBillAccountById(id[i]);
            Double billEntryAmount = oldBill.getBillEntryAmount();
            totalPrice += billEntryAmount;
        }
        String totalPriceS = String.format("%.2f", totalPrice);

        Billaccount oldBill = billAccountService.selectBillAccountById(id[0]);
        //打印小票
        Printinfo printinfo = printService.selectPrintinfoBydeptId(oldBill.getHousingId());
        if (printinfo != null) {
            HousinginfoCustom housinginfo = housinginfoService.selectHousingCustomById(oldBill.getHousingId());
            Roominfo roominfo = roominfoService.selectRoominfoById(oldBill.getRoominfoId());
            PrintMessage print = new PrintMessage(printinfo.getMachineCode(), printinfo.getMsign());
            String payType = ApplicationUtils.getPayType(oldBill.getPaytype());
            StringBuffer sb = new StringBuffer("");
            sb.append("<center>智慧小区</center>\n");
            sb.append("小区名称：" + housinginfo.getName() + "\n");
            sb.append(roominfo.getAddress() + "\n");
            sb.append("业主姓名：" + roominfo.getOwnerName() + "\n");
            sb.append("付款时间：" + DateUtils.formatDatetime(oldBill.getPaydate()) + "\n");
            sb.append("订单编号：" + oldBill.getId() + "\n");
            if (oldBill.getAlipayTradeNo() != null) {
                sb.append("支付宝订单号：" + oldBill.getAlipayTradeNo() + "\n");
            }
            sb.append("支付方式：" + payType + "\n");
            sb.append("缴费金额：" + totalPriceS + "\n");
            sb.append("缴费明细：\n");
            sb.append("----------------------\n");
//            sb.append("<table><tr><td>账期</td><td>类别</td><td>金额</td></tr>");
            for (int i = 0; i < id.length; i++) {
                Billaccount billaccount = billAccountService.selectBillAccountById(id[i]);
                Costtype costtype = costtypeService.selectCosttypeById(billaccount.getCostType());
//                sb.append("<tr><td>" + billaccount.getAcctPeriod() + "</td><td>" + costtype.getName() + "</td><td>" + billaccount.getBillEntryAmount() + "</td></tr>");

                sb.append("账期：" + billaccount.getAcctPeriod() + "\n");
                sb.append("类别：" + costtype.getName() + "\n");
                sb.append("金额：" + billaccount.getBillEntryAmount() + "\n");
            }
//            sb.append("</table>\n");
            sb.append("----------------------\n");
            sb.append("收款单位：" + housinginfo.getParentName() + "\n");
            sb.append("----------------------\n");
            sb.append("<center>交易小票</center>\n");
            boolean printStatus = print.sendContent(sb.toString());
            if (printStatus) {
                for (int i = 0; i < id.length; i++) {
                    BillAccountCustom billAccountCustom = new BillAccountCustom();
                    billAccountCustom.setId(id[i]);
                    billAccountCustom.setPrintstatus(printStatus);
                    bl = billAccountService.updateBillaccount(billAccountCustom);
                }
            }
        }
        jsonResult.setSuccess(bl);
        return jsonResult;
    }

    /**
     * 查询小区账单缴纳情况
     *
     * @param query
     * @return
     */
    @RequestMapping("/getAllGroupByStatus")
    public String getAllGroupByStatus(BillAccountCustom query, HttpServletRequest request, Model model) throws IOException {
        UserCustom loginUser = (UserCustom) request.getSession().getAttribute("userInfo");
        String code = loginUser.getParentCode();
        List<ParentCustom> housingList = housinginfoService.queryParentHousingByCode(code); //获取小区列表
        model.addAttribute("housingList", housingList);
        query.setHousingCode(code);
        BillAccountCustom billAccount = billAccountService.selectAllGroupByStatus(query); //获取小区账单状态情况
        model.addAttribute("billAccount", billAccount);
        query.setPaytype(StaticVar.BILLACCOUNT_PAYSTATUS2);
        BillAccountCustom billAccountZ = billAccountService.queryAmountGroup(query); //获取小区账单状态情况
        model.addAttribute("billAccountZ", billAccountZ);
        query.setPaytype(StaticVar.BILLACCOUNT_PAYSTATUS1);
        BillAccountCustom billAccountX = billAccountService.queryAmountGroup(query); //获取小区账单状态情况
        model.addAttribute("billAccountX", billAccountX);
        query.setPaytype(StaticVar.BILLACCOUNT_PAYSTATUS3);
        BillAccountCustom billAccountW = billAccountService.queryAmountGroup(query); //获取小区账单状态情况
        model.addAttribute("billAccountW", billAccountW);
        query.setPaytype(StaticVar.BILLACCOUNT_PAYSTATUS5);
        BillAccountCustom billAccountY = billAccountService.queryAmountGroup(query); //获取小区账单状态情况
        model.addAttribute("billAccountY", billAccountY);
        List<BillAccountCustom> payAmountList = billAccountService.queryAmountGroupByPayType(query); //获取小区账单金额
        List<SeriesData> amountList = new ArrayList<>();
        for (BillAccountCustom bill : payAmountList) {
            SeriesData seriesData = new SeriesData();
            if (bill.getPaystatus()) {
                seriesData.setName("已缴:" + bill.getSumAmount());
            } else {
                seriesData.setName("未缴:" + bill.getSumAmount());
            }
            seriesData.setSumAmount(bill.getSumAmount());
            amountList.add(seriesData);
        }
        model.addAttribute("payAmountList", JSON.toJSONString(amountList));
        List<BillAccountCustom> payCountList = billAccountService.queryCountGroupByPayType(query); //获取小区账单笔数
        List<SeriesData> countList = new ArrayList<>();
        for (BillAccountCustom bill : payCountList) {
            SeriesData seriesData = new SeriesData();
            if (bill.getPaystatus()) {
                seriesData.setName("已缴:" + bill.getCountNum());
            } else {
                seriesData.setName("未缴:" + bill.getCountNum());
            }
            seriesData.setSumNum(bill.getCountNum());
            countList.add(seriesData);
        }
        model.addAttribute("payCountList", JSON.toJSONString(countList));
        model.addAttribute("query", query);
        return "/welcome";
    }

    @RequestMapping("billAllreceiv")
    @ResponseBody
    public JSONResult billAllreceiv(Integer[] ids) {
        // TODO: 2017/12/7
        JSONResult jsonResult = new JSONResult();
        InvoiceTitle invoiceTitle = new InvoiceTitle();
        BillAccountCustom bCustom = new BillAccountCustom();
        Double totalPrice = 0.0;
        List<InvoiceTitleDetail> titleDetailList = new ArrayList<>();
        for (Integer id : ids) {
            Billaccount billaccount = billAccountService.selectBillAccountById(id);
            if (billaccount.getPaystatus()) {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("请选择未付款项进行付款操作");
                return jsonResult;
            }
            Roominfo roominfo = roominfoService.selectRoominfoById(billaccount.getRoominfoId());
            if (invoiceTitle.getBuyerPhone() != null && !roominfo.getOwnerPhone().equals(invoiceTitle.getBuyerPhone())) {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("请选择同一业主的数据");
                return jsonResult;
            }
            Housinginfo housing = housinginfoService.selectHousinginfoById(billaccount.getHousingId());
            Propertyinfo propertyinfo = propertyinfoService.selectPropertyinfoById(housing.getParentId());
            Costtype costtype = costtypeService.selectCosttypeById(billaccount.getCostType());
            //发票明细
            InvoiceTitleDetail detail = new InvoiceTitleDetail();
            detail.setGoodsName(costtype.getName() + "-" + billaccount.getAcctPeriod());
            detail.setNum("1");
            detail.setTaxRate(costtype.getTaxrate().toString());
            detail.setWithTaxFlag("1");
            detail.setPrice(billaccount.getBillEntryAmount().toString());
            titleDetailList.add(detail);
            //发票主体
            invoiceTitle.setBuyerName(roominfo.getOwnerName() + "-" + roominfo.getAddress());
            invoiceTitle.setBuyerPhone(roominfo.getOwnerPhone());
            invoiceTitle.setOrderNo(billaccount.getId().toString());
            invoiceTitle.setClerk("系统");
            invoiceTitle.setInvoiceDate(DateUtils.getCurDatetime());
            invoiceTitle.setSalerTel(propertyinfo.getContactPhone());
            invoiceTitle.setSalerAddress(propertyinfo.getContactAddress());
            invoiceTitle.setSalerTaxNum(propertyinfo.getSalertaxnum());
            invoiceTitle.setInvoiceType("1");
            invoiceTitle.setPushMode("1");
            totalPrice += billaccount.getBillEntryAmount();
        }
        bCustom.setIds(ids);
        DecimalFormat df = new DecimalFormat("0.00");
        String num = df.format(totalPrice);
        bCustom.setFkAmount(num);
        jsonResult.setSuccess(true);
        jsonResult.setData(bCustom);
        return jsonResult;
    }

    /**
     * 跳转账单收款
     *
     * @param
     * @return
     */
    @RequestMapping("/openReceivAllBillAccount")
    public String openReceivAllBillAccount(BillAccountCustom billAccountCustom, HttpServletRequest request, Model model) {
        List<Costtype> costList = costtypeService.queryAllList();
        model.addAttribute("costList", costList);
        BillAccountCustom query = new BillAccountCustom();
        query.setId(billAccountCustom.getIds()[0]);
        List<BillAccountCustom> list = billAccountService.queryBillAccountList(query);
        String idsStr = "";
        Integer[] ids = billAccountCustom.getIds();
        List<Billaccount> costTypeList = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            BillAccountCustom billaccount = billAccountService.selectBillAccountAndCostTypeById(ids[i]);
            costTypeList.add(billaccount);
            if (i == ids.length - 1) {
                idsStr += ids[i];
            } else {
                idsStr += ids[i] + ",";
            }
        }
        model.addAttribute("costTypeList", costTypeList);
        if (list.size() == 1) {
            BillAccountCustom billaccount = list.get(0);
            billaccount.setHousingCode(idsStr);
            billaccount.setIds(billAccountCustom.getIds());
            billaccount.setFkAmount(billAccountCustom.getFkAmount());
            model.addAttribute("billaccount", billaccount);
        }
        return "/billaccount/billaccount-receivAll";
    }

    /**
     * 账单收款
     *
     * @param billaccount
     * @return
     */
    @RequestMapping(path = "/receivAllBillAccount", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult receivAllBillAccount(@RequestBody BillAccountCustom billaccount, HttpSession session) {
        boolean bl = false;
        String[] ids = null;
        JSONResult jsonResult = new JSONResult();
        String housingCode = billaccount.getHousingCode();
        boolean contains = housingCode.contains(",");
        Billaccount oldBill = null;
        Integer[] idInt = null;
        for (int i = 0; i < billaccount.getBillList().size(); i++) {
            BillAccountCustom billAccountCustom = billaccount.getBillList().get(i);
            billAccountService.updateByPrimaryKeySelective(billAccountCustom);
        }
        if (!contains) {
            idInt = new Integer[1];
            ids = new String[1];
            ids[0] = housingCode;
            idInt[0] = Integer.valueOf(housingCode);
            billaccount.setId(Integer.valueOf(housingCode));
            oldBill = billAccountService.selectBillAccountById(Integer.valueOf(housingCode));
        } else {
            ids = housingCode.split(",");
            idInt = new Integer[ids.length];
            oldBill = billAccountService.selectBillAccountById(Integer.valueOf(ids[0]));
        }
        //删除支付宝账单
        if (oldBill.getStatus()) {
            UserCustom loginUser = (UserCustom) session.getAttribute("userInfo");
            HousinginfoCustom housing = housinginfoService.selectHousingCustomById(oldBill.getHousingId());
            List<String> bill_entry_id_list = new ArrayList<>();
            for (int i = 0; i < ids.length; i++) {
                bill_entry_id_list.add(ids[i]);
            }
            alipayService.billDeleteRequest(housing.getCommunityId(), bill_entry_id_list, housing.getToken(), loginUser);
        }
        //更新收款信息

        for (int i = 0; i < ids.length; i++) {
            //BillAccountCustom billAccountCustom = new BillAccountCustom();
            billaccount.setId(Integer.valueOf(ids[i]));
            billaccount.setPaystatus(true);
            billaccount.setPaydate(new Date());
            bl = billAccountService.updateBillaccount(billaccount);
            idInt[i] = Integer.valueOf(ids[i]);
        }
        //打印小票

        printAccount(idInt);
        jsonResult.setSuccess(bl);
        return jsonResult;
    }

    /**
     * 下载电子发票
     *
     * @param query
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/downloadInvoiceList")
    public void downloadInvoiceList(BillAccountCustom query, HttpServletRequest request, Model model, HttpServletResponse response) {
        UserCustom loginUser = (UserCustom) request.getSession().getAttribute("userInfo");
        String parentCode = loginUser.getParentCode();
        query.setHousingCode(parentCode);
        query.setPaystatus(true);
        HSSFWorkbook workbook = billAccountService.exportBillAccount(query);
        HttpServletResponse httpResponse = response;
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setHeader("Content-Disposition ", "attachment; filename=downloadInvoiceList.xls");
        httpResponse.setContentType("application/vnd.ms-excel");
        try {
            ServletOutputStream outputStream = httpResponse.getOutputStream();
            workbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载我的账单
     *
     * @param query
     * @return
     */
    @RequestMapping("/downloadBillAccountList")
    public void downloadBillAccountList(HttpServletRequest request, BillAccountCustom query, HttpServletResponse response) {
        UserCustom loginUser = (UserCustom) request.getSession().getAttribute("userInfo");
        String parentCode = loginUser.getParentCode();
        query.setHousingCode(parentCode);
        HSSFWorkbook workbook = billAccountService.exportBillAccountList(query);
        HttpServletResponse httpResponse = response;
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setHeader("Content-Disposition ", "attachment; filename=downloadBillAccountList.xls");
        httpResponse.setContentType("application/vnd.ms-excel");
        try {
            ServletOutputStream outputStream = httpResponse.getOutputStream();
            workbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据部门code查询账单信息
     *
     * @param query
     * @return
     */
    @RequestMapping("/tradeCenterList")
    public String tradeCenterList(BillAccountCustom query, HttpServletRequest request, Model model) {
        UserCustom loginUser = (UserCustom) request.getSession().getAttribute("userInfo");
        String parentCode = loginUser.getParentCode();
        List<ParentCustom> parentList = housinginfoService.queryParentHousingByCode(loginUser.getParentCode());
        model.addAttribute("parentList", parentList);
        query.setHousingCode(parentCode);
        List<Costtype> costList = costtypeService.queryAllList();
        model.addAttribute("costList", costList);
        return "/tradeCenter/tradeCenter-list";
    }

    /**
     * 根据部门code查询账单信息
     *
     * @param query
     * @return
     */
    @RequestMapping("/tableTradeCenter")
    @ResponseBody
    public DataTable tableTradeCenter(BillAccountCustom query, HttpServletRequest request) {
        DataTable table = new DataTable();
        UserCustom loginUser = (UserCustom) request.getSession().getAttribute("userInfo");
        String parentCode = loginUser.getParentCode();
        query.setHousingCode(parentCode);
        Date endTime = query.getEndTime();
        Date startTime = query.getStartTime();
        if (endTime != null && startTime != null) {
            SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
            boolean equals = fmt.format(startTime).equals(fmt.format(endTime));
            if (equals) {
                Calendar c = Calendar.getInstance();
                c.setTime(endTime);
                c.add(Calendar.DAY_OF_MONTH, 1);// 今天+1天
                Date tomorrow = c.getTime();
                query.setEndTime(tomorrow);
            }
        }
        List<BillAccountCustom> list = billAccountService.getTradeCenterList(query);
        table.setRecordsFiltered(1);
        table.setRecordsTotal(1);
        table.setData(list);
        return table;
    }

    /**
     * 工作报表统计
     *
     * @param query
     * @return
     */
    @RequestMapping("/workReportList")
    public String workReportList(BillAccountCustom query, HttpServletRequest request, Model model) {
        UserCustom loginUser = (UserCustom) request.getSession().getAttribute("userInfo");
        List<ParentCustom> parentList = housinginfoService.queryParentHousingByCode(loginUser.getParentCode());
        query.setHousingCode(loginUser.getParentCode());
        List<BillAccountCustom> acctPeriodList = billAccountService.billAccountAcct(query);
        model.addAttribute("acctPeriodList", acctPeriodList);
        model.addAttribute("parentList", parentList);
        return "/workReport/workReport-list";
    }

    /**
     * 工作报表统计
     *
     * @param query
     * @return
     */
    @RequestMapping("/tableWorkReport")
    @ResponseBody
    public DataTable tableWorkReport(BillAccountCustom query, HttpServletRequest request) {
        DataTable table = new DataTable();
        List<BillAccountCustom> billAccountCustomList = new ArrayList<>();
        UserCustom loginUser = (UserCustom) request.getSession().getAttribute("userInfo");
        String parentCode = loginUser.getParentCode();
        query.setHousingCode(parentCode);
//        if (query.getEndTime() != null && query.getStartTime() != null) {
//            SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
//            boolean equals = fmt.format(query.getStartTime()).equals(fmt.format(query.getEndTime()));
//            if (equals) {
//                Date endTime = query.getEndTime();
//                Calendar c = Calendar.getInstance();
//                c.setTime(endTime);
//                c.add(Calendar.DAY_OF_MONTH, 1);// 今天+1天
//                Date tomorrow = c.getTime();
//                query.setEndTime(tomorrow);
//            }
//        }
        List<BillAccountCustom> billAccountCustom = billAccountService.tableWorkReport(query);
        table.setRecordsFiltered(1);
        table.setRecordsTotal(1);
        table.setData(billAccountCustom);
        return table;
    }

    @RequestMapping("billAccountAcct")
    @ResponseBody
    public List<BillAccountCustom> billAccountAcct(BillAccountCustom billAccountCustom, HttpSession session) {
        UserCustom userCustom = (UserCustom) session.getAttribute("userInfo");
        billAccountCustom.setHousingCode(userCustom.getParentCode());
        List<BillAccountCustom> billAccountCustomList = billAccountService.billAccountAcct(billAccountCustom);
        return billAccountCustomList;
    }

    @RequestMapping("deleteTicket")
    @ResponseBody
    public JSONResult deleteTicket(Integer id) {
        JSONResult jsonResult = new JSONResult();
        directFeeService.deleteByPrimaryKey(id);
        jsonResult.setSuccess(true);
        jsonResult.setMessage("删除成功");
        return jsonResult;
    }
}
